# __*__ coding:utf-8 __*__
import os

import pexpect
import logging

timeout = 2


def generate_key1(child):
    child.sendline("")
    res = child.expect(
        ["Overwrite", "Enter passphrase"]
    )
    if res == 0:
        child.sendline("n")
    else:
        child.sendline("")
        child.expect("Enter same passphrase again")
        child.sendline("")


def gen_ssh_key(user, password, ip):
    child = pexpect.spawn(f"ssh {user}@{ip} ssh-keygen", timeout=timeout)
    res1 = child.expect(
        ["Enter file in which to save the key", "Are you sure you want to continue connecting", "password"], timeout=2
    )
    if res1 == 0:
        generate_key1(child)
    elif res1 == 1:
        child.sendline("yes")
        child.expect("password")
        child.sendline(password)
        child.expect("Enter file in which to save the key")
        generate_key1(child)
    else:
        child.sendline(password)
        child.expect("Enter file in which to save the key")
        generate_key1(child)


def ssh_copy_id_f(user, password, ip):
    child = pexpect.spawn(f"ssh-copy-id {user}@{ip}")
    res = child.expect(
        ["password", "exist on the remote system"], timeout=2
    )
    if res == 0:
        child.sendline(password)
        child.expect(pexpect.EOF)
    elif res == 1:
        print("已上传公钥")
    else:
        print("未知错误")


def get_login_auth(user, password, ip):
    gen_ssh_key(user, password, ip)
    ssh_copy_id_f(user, password, ip)


if __name__ == '__main__':
    get_login_auth('python', "zdx134278", "192.168.132.77")
